package com.easylinkin.linkappapi.hcmy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.NumberUtil;
import com.easylinkin.linkappapi.hcmy.entity.LivestockFarmers;
import com.easylinkin.linkappapi.hcmy.entity.LivestockFarming;
import com.easylinkin.linkappapi.hcmy.entity.LivestockFarmingStatistic;
import com.easylinkin.linkappapi.hcmy.entity.LivestockStatistic;
import com.easylinkin.linkappapi.hcmy.mapper.LivestockFarmersMapper;
import com.easylinkin.linkappapi.hcmy.mapper.LivestockFarmingMapper;
import com.easylinkin.linkappapi.hcmy.service.LivestockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * class info :畜禽养殖业务层
 *
 * @author liuqihang
 * @date 2021/10/15 17:41
 */
@Slf4j
@Service
public class LivestockServiceImpl implements LivestockService {

    @Resource
    private LivestockFarmersMapper livestockFarmersMapper;
    @Resource
    private LivestockFarmingMapper livestockFarmingMapper;
    @Resource
    private CommonService commonService;

    @Override
    public String saveLivestockFarmingData(LivestockFarming livestockFarming) {
        Assert.notNull(livestockFarming.getStatisticYear(), "统计年度不能为空");
        Assert.notNull(livestockFarming.getSpaceId(), "示范区不能为空");
        Assert.notNull(livestockFarming.getAreaId(), "示范村不能为空");
        QueryWrapper qw2 = new QueryWrapper();
        qw2.eq("statistic_year", livestockFarming.getStatisticYear());
        qw2.eq("space_id", livestockFarming.getSpaceId());
        qw2.eq("area_id", livestockFarming.getAreaId());
        List list = livestockFarmingMapper.selectList(qw2);
        if(ObjectUtils.isNotEmpty(list)){
            return "统计年度、示范区和示范村数据重复";
        }

        commonService.setCreateAndModifyInfo(livestockFarming);
        commonService.setTenantIdInfo(livestockFarming);
        livestockFarmingMapper.insert(livestockFarming);
        return null;
    }

    @Override
    public String updateLivestockFarmingData(LivestockFarming livestockFarming) {
        Assert.notNull(livestockFarming.getId(), "id不能为空");
        Assert.notNull(livestockFarming.getStatisticYear(), "统计年度不能为空");
        Assert.notNull(livestockFarming.getSpaceId(), "示范区不能为空");
        Assert.notNull(livestockFarming.getAreaId(), "示范村不能为空");
        QueryWrapper qw2 = new QueryWrapper();
        qw2.notIn("id", livestockFarming.getId());
        qw2.eq("statistic_year", livestockFarming.getStatisticYear());
        qw2.eq("space_id", livestockFarming.getSpaceId());
        qw2.eq("area_id", livestockFarming.getAreaId());
        List list = livestockFarmingMapper.selectList(qw2);
        if(ObjectUtils.isNotEmpty(list)){
            return "统计年度、示范区和示范村数据重复";
        }

        commonService.setModifyInfo(livestockFarming);
        livestockFarmingMapper.updateById(livestockFarming);
        return null;
    }

    @Override
    public String deleteLivestockFarmingData(LivestockFarming livestockFarming) {
        Assert.notNull(livestockFarming.getBatchId(), "批量删除ID参数不能为空");
        String[] split = livestockFarming.getBatchId().split(",");
        int[] array = Arrays.asList(split).stream().mapToInt(Integer::parseInt).toArray();
        if(array.length == 1){
            livestockFarmingMapper.deleteById(array[0]);
        }else {
            List<Integer> idList = Arrays.stream(array).boxed().collect(Collectors.toList());
            livestockFarmingMapper.deleteBatchIds(idList);
        }
        return null;
    }

    @Override
    public IPage<LivestockFarming> getLivestockFarmingPage(Page page, LivestockFarming livestockFarming) {
        commonService.setTenantIdInfo(livestockFarming);
        return livestockFarmingMapper.getLivestockFarmingPage(page, livestockFarming);
    }


    @Override
    public String saveLivestockFarmersData(LivestockFarmers livestockFarmers) {
        Assert.notNull(livestockFarmers.getStatisticYear(), "统计年度不能为空");
        Assert.notNull(livestockFarmers.getSpaceId(), "示范区不能为空");
        Assert.notNull(livestockFarmers.getAreaId(), "示范村不能为空");
        QueryWrapper qw2 = new QueryWrapper();
        qw2.eq("statistic_year", livestockFarmers.getStatisticYear());
        qw2.eq("space_id", livestockFarmers.getSpaceId());
        qw2.eq("area_id", livestockFarmers.getAreaId());
        List list = livestockFarmersMapper.selectList(qw2);
        if(ObjectUtils.isNotEmpty(list)){
            return "统计年度、示范区和示范村数据重复";
        }
        commonService.setCreateAndModifyInfo(livestockFarmers);
        commonService.setTenantIdInfo(livestockFarmers);
        livestockFarmersMapper.insert(livestockFarmers);
        return null;
    }

    @Override
    public String updateLivestockFarmersData(LivestockFarmers livestockFarmers) {
        Assert.notNull(livestockFarmers.getId(), "id不能为空");
        Assert.notNull(livestockFarmers.getStatisticYear(), "统计年度不能为空");
        Assert.notNull(livestockFarmers.getSpaceId(), "示范区不能为空");
        Assert.notNull(livestockFarmers.getAreaId(), "示范村不能为空");

        QueryWrapper qw2 = new QueryWrapper();
        qw2.notIn("id", livestockFarmers.getId());
        qw2.eq("statistic_year", livestockFarmers.getStatisticYear());
        qw2.eq("space_id", livestockFarmers.getSpaceId());
        qw2.eq("area_id", livestockFarmers.getAreaId());
        List list = livestockFarmersMapper.selectList(qw2);
        if(ObjectUtils.isNotEmpty(list)){
            return "统计年度、示范区和示范村数据重复";
        }

        commonService.setModifyInfo(livestockFarmers);
        livestockFarmersMapper.updateById(livestockFarmers);
        return null;
    }

    @Override
    public String deleteLivestockFarmersData(LivestockFarmers livestockFarmers) {
        Assert.notNull(livestockFarmers.getBatchId(), "批量删除ID参数不能为空");
        String[] split = livestockFarmers.getBatchId().split(",");
        int[] array = Arrays.asList(split).stream().mapToInt(Integer::parseInt).toArray();
        if(array.length == 1){
            livestockFarmersMapper.deleteById(array[0]);
        }else {
            List<Integer> idList = Arrays.stream(array).boxed().collect(Collectors.toList());
            livestockFarmersMapper.deleteBatchIds(idList);
        }
        return null;
    }

    @Override
    public IPage<LivestockFarmers> getLivestockFarmersPage(Page page, LivestockFarmers livestockFarmers) {
        commonService.setTenantIdInfo(livestockFarmers);
        return livestockFarmersMapper.getLivestockFarmersPage(page, livestockFarmers);
    }

    /**
     * 公用获取畜禽养殖数据统计
     * @param page
     * @param livestockFarming
     * @return
     */
    private IPage<LivestockFarmingStatistic> getLivestockFarmingStatisticPage(Page page, LivestockFarming livestockFarming){
        commonService.setTenantIdInfo(livestockFarming);
        IPage<LivestockFarmingStatistic> livestockFarmingStatisticPage = livestockFarmingMapper.getLivestockFarmingStatisticPage(page, livestockFarming);
        return livestockFarmingStatisticPage;
    }

    @Override
    public IPage<LivestockStatistic> getLivestockFarmingPollutantDischargePage(Page page, LivestockFarming livestockFarming) {
        Page<LivestockStatistic> lsPage = new Page<>();

        IPage<LivestockFarmingStatistic> livestockFarmingStatisticPage = getLivestockFarmingStatisticPage(page, livestockFarming);
        if(livestockFarmingStatisticPage == null || ObjectUtils.isEmpty(livestockFarmingStatisticPage.getRecords())){
            return lsPage;
        }
        lsPage.setSize(page.getSize());
        lsPage.setCurrent(page.getCurrent());
        lsPage.setTotal(livestockFarmingStatisticPage.getTotal());
        List<LivestockFarmingStatistic> records = livestockFarmingStatisticPage.getRecords();
        List<LivestockStatistic> resultList = new ArrayList<>();
        records.forEach(livestockFarmingStatistic -> {
            LivestockStatistic ls = new LivestockStatistic();
            //总猪数量
            long pigTotalNum = getPigTotalNum(livestockFarmingStatistic);
            long factor = 1000*1000;
            ls.setStatisticYear(livestockFarmingStatistic.getStatisticYear());
            ls.setSpaceName(livestockFarmingStatistic.getSpaceName());
            ls.setCod(calculateEmissions(new BigDecimal("181.22"), pigTotalNum, factor));
            ls.setTotalN(calculateEmissions(new BigDecimal("17.92"), pigTotalNum, factor));
            ls.setTotalP(calculateEmissions(new BigDecimal("3.13"), pigTotalNum, factor));
            resultList.add(ls);
        });
        lsPage.setRecords(resultList);
        return lsPage;
    }

    @Override
    public IPage<LivestockStatistic> getPigManureSewagePage(Page page, LivestockFarming livestockFarming) {
        Page<LivestockStatistic> lsPage = new Page<>();

        IPage<LivestockFarmingStatistic> livestockFarmingStatisticPage = getLivestockFarmingStatisticPage(page, livestockFarming);
        if(livestockFarmingStatisticPage == null || ObjectUtils.isEmpty(livestockFarmingStatisticPage.getRecords())){
            return lsPage;
        }
        lsPage.setSize(page.getSize());
        lsPage.setCurrent(page.getCurrent());
        lsPage.setTotal(livestockFarmingStatisticPage.getTotal());
        List<LivestockFarmingStatistic> records = livestockFarmingStatisticPage.getRecords();
        List<LivestockStatistic> resultList = new ArrayList<>();
        records.forEach(livestockFarmingStatistic -> {
            LivestockStatistic ls = new LivestockStatistic();
            //总猪数量
            long pigTotalNum = getPigTotalNum(livestockFarmingStatistic);
            long factor = 1000;
            ls.setStatisticYear(livestockFarmingStatistic.getStatisticYear());
            ls.setSpaceName(livestockFarmingStatistic.getSpaceName());
            ls.setPigManure(calculateEmissions(new BigDecimal("1.18"), pigTotalNum, factor));
            ls.setFarmingSewage(calculateEmissions(new BigDecimal("3.18"), pigTotalNum, factor));
            resultList.add(ls);
        });
        lsPage.setRecords(resultList);
        return lsPage;
    }

    /************************************************ 数量转换和计算 ****************************************/

    /**
     * 获取数据转换后 猪的总数量
     * @param livestockFarmingStatistic
     * @return
     */
    private int getPigTotalNum(LivestockFarmingStatistic livestockFarmingStatistic){
        int totalNum = 0;
        totalNum += livestockFarmingStatistic.getPigTotalNum();
        totalNum += getPigNumByMeatPoultry(livestockFarmingStatistic.getMeatPoultryTotalNum());
        totalNum += getPigNumByEgg(livestockFarmingStatistic.getEggTotalNum());
        totalNum += getPigNumBySheep(livestockFarmingStatistic.getSheepTotalNum());
        totalNum += getPigNumByCattle(livestockFarmingStatistic.getCattleTotalNum());
        return totalNum;
    }

    /**
     * 计算排放量，数值单位转换为 吨
     * @param gram
     * @param pigTotalNum
     * @return
     */
    private BigDecimal calculateEmissions(BigDecimal gram, long pigTotalNum, long factor){
        //一年总排放量，单位“克”
        BigDecimal multiply = gram.multiply(new BigDecimal(pigTotalNum*365));
        //转换为“吨”
        BigDecimal ton = multiply.divide(new BigDecimal(factor));
        ton = NumberUtil.bigDecimalRoundHalfUp(ton, 3);
        return ton;
    }

    /**
     * 蛋鸡数量转换为猪数量
     * @param egg
     * @return
     */
    private int getPigNumByEgg(Integer egg){
        int result = 0;
        if(egg == null){
            return result;
        }
        double ceil = Math.floor(egg / 30);
        result = (int)ceil;
        return result;
    }

    /**
     * 肉禽数量转换为猪数量
     * @param meatPoultry
     * @return
     */
    private int getPigNumByMeatPoultry(Integer meatPoultry){
        int result = 0;
        if(meatPoultry == null){
            return result;
        }
        double ceil = Math.floor(meatPoultry / 60);
        result = (int)ceil;
        return result;
    }

    /**
     * 羊数量转换为猪数量
     * @param sheep
     * @return
     */
    private int getPigNumBySheep(Integer sheep){
        int result = 0;
        if(sheep == null){
            return result;
        }
        double ceil = Math.floor(sheep / 3);
        result = (int)ceil;
        return result;
    }

    /**
     * 牛数量转换为猪数量
     * @param cattle
     * @return
     */
    private int getPigNumByCattle(Integer cattle){
        int result = 0;
        if(cattle == null){
            return result;
        }
        result = cattle*5;
        return result;
    }
}
